package com.stkcall.library;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.text.TextUtils;
import android.util.Log;

import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.XXPermissions;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

import static android.content.Context.BIND_AUTO_CREATE;

/**
 * <p>------------------------------------------------------
 * <p>Copyright (C) company, All rights reserved.
 * <p>------------------------------------------------------
 * 录音管理器
 * @author: xujie
 * @date: 7/15/22
 */
public class RecordAudioManager {
    private static final String TAG = "RecordAudioManager";

    private static final String XIAOMI_SETTING = "com.android.phone.settings.CallRecordSetting";
    private static final String HUAWEI_SETTING = "com.android.phone.MSimCallFeaturesSetting";
    private static final String OPPO_SETTING = "com.android.phone.OppoCallFeaturesSetting";
    private static final String OTHER_SETTING = "com.android.phone.CallFeaturesSetting";

    private String mCurrentSetting;//录音开关设计
    private String mCurrentKey;//录音开关
    private String mRecordAudioFile;//设置录音目录
    private long mTimeNode;//设置时间点

    @SuppressLint("StaticFieldLeak")
    private static RecordAudioManager INSTANCE;
    private Context context;
    private List<File> fileList = new ArrayList<>();
    private int maxValue = 50;
    private OnPermissionCallback callback;
    private boolean isGrantedAllPermission = false;
    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            CallListenerService.MyBinder binder = (CallListenerService.MyBinder) service;
            CallListenerService service1 = binder.getService();
            Log.d(TAG, "onServiceConnected: " + service1.getPackageName());
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.d(TAG, "onServiceDisconnected: ");
        }
    };

    public static synchronized RecordAudioManager getInstance(){
        synchronized (RecordAudioManager.class){
            if(INSTANCE == null) {

                INSTANCE = new RecordAudioManager();
            }
        }
        return INSTANCE;
    }
    private RecordAudioManager(){}

    public void init(Activity context){
        this.context = context;

        XXPermissions.with(context)
                .permission(Arrays.asList(Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.CALL_PHONE,
                        Manifest.permission.READ_PHONE_STATE,
                        Manifest.permission.READ_CALL_LOG))
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        isGrantedAllPermission = all;
                        if(all){
                            context.bindService(new Intent(context, CallListenerService.class),serviceConnection,BIND_AUTO_CREATE);
                        }
                        if(callback != null){
                            callback.onGranted(permissions, all);
                        }

                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        isGrantedAllPermission = false;

                        if (callback != null){
                            callback.onDenied(permissions, never);
                        }
                    }
                });
    }

    public void deInit(){
        context.unbindService(serviceConnection);
    }

    /**
     * 是否已授予所有权限
     * @return
     */
    public boolean isGrantedAllPermission(){
        return isGrantedAllPermission;
    }

    /**
     * 权限回调
     * @param callback
     */
    public void setOnPermissionCallback(OnPermissionCallback callback){
        this.callback = callback;
    }

    /**
     * 设置文件数量最大值
     * @param maxValue
     * @return
     */
    public RecordAudioManager setFileListMaxValue(int maxValue){
        this.maxValue = maxValue;
        return this;
    }

    /**
     * 设置录音开关设置页
     * @param className
     * @return
     */
    public RecordAudioManager setRecordAudioSetting(String className){
        this.mCurrentSetting = className;
        return this;
    }

    /**
     * 设置录音开关值
     * @param key
     * @return
     */
    public RecordAudioManager setRecordAudioKey(String key){
        this.mCurrentKey = key;
        return this;
    }

    /**
     * 设置录音文件查询目录
     * @param recordAudioFile
     * @return
     */
    public RecordAudioManager setRecordSearchAudioFile(String recordAudioFile){
        this.mRecordAudioFile = recordAudioFile;
        return this;
    }

    /**
     * 设置录音时间节点
     * @param timeNode
     * @return
     */
    public RecordAudioManager setRecordTimeNode(long timeNode){
        this.mTimeNode = timeNode;
        Log.d(TAG, "setRecordTimeNode: " + timeNode);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String format = sdf.format(timeNode);
        Log.d(TAG, "setRecordTimeNode: " + format);
        return this;
    }

    /**
     * 打开设置页
     * @param context
     */
    public void openSetting(Context context){
        if(TextUtils.isEmpty(mCurrentSetting)){
            if(DeviceUtils.getDeviceManufacturer().equalsIgnoreCase("OPPO")){
                DeviceUtils.gotoRecordAudioSetting(context,OPPO_SETTING);
            }else if(DeviceUtils.getDeviceManufacturer().equalsIgnoreCase("XIAOMI")){
                DeviceUtils.gotoRecordAudioSetting(context,XIAOMI_SETTING);
            }else if(DeviceUtils.getDeviceManufacturer().equalsIgnoreCase("HUAWEI") || DeviceUtils.getDeviceManufacturer().equalsIgnoreCase("HONOR")){
                DeviceUtils.gotoRecordAudioSetting(context,HUAWEI_SETTING);
            }else {
                DeviceUtils.gotoRecordAudioSetting(context, OTHER_SETTING);
            }
        }else {
            DeviceUtils.gotoRecordAudioSetting(context,mCurrentSetting);
        }
    }

    /**
     * 检查录音权限是否开启
     * @return
     */
    public int checkRecordAudioSwitch(Context context){

        if(TextUtils.isEmpty(mCurrentKey)){
            if(DeviceUtils.getDeviceManufacturer().equalsIgnoreCase("OPPO")){
                return DeviceUtils.checkOppoRecord(context);
            }else if(DeviceUtils.getDeviceManufacturer().equalsIgnoreCase("XIAOMI")){
                return DeviceUtils.checkXiaomiRecord(context);
            }else if(DeviceUtils.getDeviceManufacturer().equalsIgnoreCase("HUAWEI") || DeviceUtils.getDeviceManufacturer().equalsIgnoreCase("HONOR")){
                return DeviceUtils.checkHuaweiRecord(context);
            }else {
                return -1;
            }
        }else {
            return DeviceUtils.checkRecord(context,mCurrentKey);
        }
    }

    /**
     * 删除文件
     * @param file
     * @return
     */
    public boolean deleteFile(File file){
        if(file.exists()){
            return file.delete();
        }
        return false;
    }

    /**
     * 查询最新的录音文件
     * @return
     */
    public File searchAudioLastFile(){
        List<File> fileList = searchAudioFile();
        File lastFile = null;
        if(fileList.size() > 0){
            lastFile = fileList.get(0);
        }
        if(lastFile != null && mTimeNode != 0){
            long l = lastFile.lastModified();
            if(l < mTimeNode){
                lastFile = null;
            }
        }
        return lastFile;
    }

    /**
     * 查询录音列表
     * @return
     */
    public List<File> searchAudioFile(){
        fileList = new ArrayList<>();
        Log.d(TAG, "searchAudio: ");
        List<File> dirList = new ArrayList<>();
        if(TextUtils.isEmpty(mRecordAudioFile)) {
            File file = AutoVoiceFileUtils.pathFile();
            dirList.add(file);
        }else {
            if(mRecordAudioFile.contains(",")){
                String[] files = mRecordAudioFile.split(",");
                for (String p:files) {
                    dirList.add(AutoVoiceFileUtils.getRecordFile(p));
                }
            }else {
                dirList.add(AutoVoiceFileUtils.getRecordFile(mRecordAudioFile));
            }
        }
        if(!dirList.isEmpty()) {
            Log.d(TAG, "searchAudioFile: ");
            for (File dir:dirList) {
                File[] files = dir.listFiles();
                if(files != null && files.length > 0) {
                    for (File f : files) {
                        loopAudioFile(f);
                    }
                }
            }
        }else {
            Log.d(TAG, "searchAudioFile: null");
        }

        //排序
        Collections.sort(fileList, new Comparator<File>() {
            @Override
            public int compare(File o1, File o2) {
                return Long.compare(o2.lastModified(), o1.lastModified());
            }
        });

        return fileList.subList(0, maxValue == -1 ? fileList.size() : Math.min(fileList.size(), maxValue));
    }

    /**
     * 循环检索录音文件
     * @param file
     */
    private void loopAudioFile(File file){
        if (file.isDirectory()){
            File[] files = file.listFiles();
            for (File f:files){
                loopAudioFile(f);
            }
        }else {
            if(mTimeNode != 0){
                long l = file.lastModified();
                if(l > mTimeNode){
                    fileList.add(file);
                }
            }else {
                fileList.add(file);
            }
        }
    }
}
